package pl.iachoo.ctl.tabory.dao.core.mybatis.impl;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import pl.iachoo.ctl.tabory.dao.api.services.IUserRoleService;

public class ServiceManager {

	private final static Logger logger = Logger.getLogger(ServiceManager.class);

	private static SqlSessionFactory sessionFactory;

	static {
		logger.info("Static build of SessionManager.");
		try {
			String resource = "myBatis.xml";
			logger.info("Reading resource: " + resource);
			Reader reader = Resources.getResourceAsReader(resource);
			logger.info("Building sql session factory...");
			if (sessionFactory == null) {
				sessionFactory = new SqlSessionFactoryBuilder().build(reader);
			}
			logger.info("Session factory created.");
			reader.close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	// static {
	// DataSource dataSource = CtlDataSourceFactory.getCtlDataSource();
	// TransactionFactory transactionFactory = new JdbcTransactionFactory();
	// Environment environment = new Environment("development",
	// transactionFactory, dataSource);
	// Configuration configuration = new Configuration(environment);
	// configuration.addMapper(UserRoleMapper.class);
	// sessionFactory = new SqlSessionFactoryBuilder().build(configuration);
	// }

	public static IUserRoleService getUserRoleService() {
		UserRoleServiceImpl serviceImpl = new UserRoleServiceImpl(
				sessionFactory);
		return serviceImpl;
	}
}
